/**
  ******************************************************************************
  * @file    Cortex/CORTEXM_Cache/Src/main.c 
  * @author  MCD Application Team
  * @brief   This example provides a description of how to do Data-Cache 
  *          maintenance on a shared memory buffer accessed by 2 masters
  *          (CPU and DMA).
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2016 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "main.h"

/** @addtogroup STM32F7xx_HAL_Examples
  * @{
  */

/** @addtogroup CORTEXM_Cache
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* DMA Handle declaration */
DMA_HandleTypeDef     DmaHandle;

static const uint32_t aSRC_Const_Buffer1[BUFFER_SIZE] =
{
  0x01020304, 0x05060708, 0x090A0B0C, 0x0D0E0F10,  0x11121314, 0x15161718, 0x191A1B1C, 0x1D1E1F20,
  0x21222324, 0x25262728, 0x292A2B2C, 0x2D2E2F30,  0x31323334, 0x35363738, 0x393A3B3C, 0x3D3E3F40,
  0x41424344, 0x45464748, 0x494A4B4C, 0x4D4E4F50,  0x51525354, 0x55565758, 0x595A5B5C, 0x5D5E5F60,
  0x61626364, 0x65666768, 0x696A6B6C, 0x6D6E6F70,  0x71727374, 0x75767778, 0x797A7B7C, 0x7D7E7F80,
  0x01020304, 0x05060708, 0x090A0B0C, 0x0D0E0F10,  0x11121314, 0x15161718, 0x191A1B1C, 0x1D1E1F20,
  0x21222324, 0x25262728, 0x292A2B2C, 0x2D2E2F30,  0x31323334, 0x35363738, 0x393A3B3C, 0x3D3E3F40,
  0x41424344, 0x45464748, 0x494A4B4C, 0x4D4E4F50,  0x51525354, 0x55565758, 0x595A5B5C, 0x5D5E5F60,
  0x61626364, 0x65666768, 0x696A6B6C, 0x6D6E6F70,  0x71727374, 0x75767778, 0x797A7B7C, 0x7D7E7F80,
  0x01020304, 0x05060708, 0x090A0B0C, 0x0D0E0F10,  0x11121314, 0x15161718, 0x191A1B1C, 0x1D1E1F20,
  0x21222324, 0x25262728, 0x292A2B2C, 0x2D2E2F30,  0x31323334, 0x35363738, 0x393A3B3C, 0x3D3E3F40,
  0x41424344, 0x45464748, 0x494A4B4C, 0x4D4E4F50,  0x51525354, 0x55565758, 0x595A5B5C, 0x5D5E5F60,
  0x61626364, 0x65666768, 0x696A6B6C, 0x6D6E6F70,  0x71727374, 0x75767778, 0x797A7B7C, 0x7D7E7F80,
  0x01020304, 0x05060708, 0x090A0B0C, 0x0D0E0F10,  0x11121314, 0x15161718, 0x191A1B1C, 0x1D1E1F20,
  0x21222324, 0x25262728, 0x292A2B2C, 0x2D2E2F30,  0x31323334, 0x35363738, 0x393A3B3C, 0x3D3E3F40,
  0x41424344, 0x45464748, 0x494A4B4C, 0x4D4E4F50,  0x51525354, 0x55565758, 0x595A5B5C, 0x5D5E5F60,
  0x61626364, 0x65666768, 0x696A6B6C, 0x6D6E6F70,  0x71727374, 0x75767778, 0x797A7B7C, 0x7D7E7F80,
  0x01020304, 0x05060708, 0x090A0B0C, 0x0D0E0F10,  0x11121314, 0x15161718, 0x191A1B1C, 0x1D1E1F20,
  0x21222324, 0x25262728, 0x292A2B2C, 0x2D2E2F30,  0x31323334, 0x35363738, 0x393A3B3C, 0x3D3E3F40,
  0x41424344, 0x45464748, 0x494A4B4C, 0x4D4E4F50,  0x51525354, 0x55565758, 0x595A5B5C, 0x5D5E5F60,
  0x61626364, 0x65666768, 0x696A6B6C, 0x6D6E6F70,  0x71727374, 0x75767778, 0x797A7B7C, 0x7D7E7F80
};

/* Use ALIGN_32BYTES() to align the destination buffer 1 on 32-byte boundary */
ALIGN_32BYTES(static uint32_t aDST_Buffer1[BUFFER_SIZE]) = {0};

/* Use ALIGN_32BYTES() to align the source buffer 2 on 32-byte boundary */
ALIGN_32BYTES(static uint32_t aSRC_Buffer2[BUFFER_SIZE]);

/* Allocate Destination Buffer 2 in non-cacheable memory (SRAM2) */
#if defined ( __ICCARM__ )
#pragma location = 0x2007C000
static uint32_t aDST_NonCacheable_Buffer2[BUFFER_SIZE];

static __IO uint32_t transferErrorDetected = 0;
static __IO uint32_t transferCompleteDetected = 0;

static uint32_t tempValue;
static uint32_t i;

#elif defined ( __CC_ARM )
static uint32_t aDST_NonCacheable_Buffer2[BUFFER_SIZE] __attribute__((section ("SRAM2")));

static __IO uint32_t transferErrorDetected __attribute__((section ("SRAM2"))) = 0 ;
static __IO uint32_t transferCompleteDetected __attribute__((section ("SRAM2")))= 0;

static uint32_t tempValue __attribute__((section ("SRAM2")));
static uint32_t i __attribute__((section ("SRAM2")));

#elif defined ( __GNUC__ )
static uint32_t aDST_NonCacheable_Buffer2[BUFFER_SIZE];

static __IO uint32_t transferErrorDetected __attribute__((section ("SRAM2"))) = 0 ;
static __IO uint32_t transferCompleteDetected __attribute__((section ("SRAM2"))) = 0 ;

static uint32_t tempValue __attribute__((section ("SRAM2")));
static uint32_t i __attribute__((section ("SRAM2")));
#endif

/* Private function prototypes -----------------------------------------------*/
static void DMA_Config(void);
static uint32_t DMA_StartAndCompare(uint32_t* SrcBuffer, uint32_t* DstBuffer, uint32_t BufferLength);
static void TransferComplete(DMA_HandleTypeDef *DmaHandle);
static void TransferError(DMA_HandleTypeDef *DmaHandle);
static void SystemClock_Config(void);
static void Error_Handler(void);
static void CPU_CACHE_Enable(void);

/* Private functions ---------------------------------------------------------*/

/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* Enable the CPU Cache */
  CPU_CACHE_Enable();
  
  /* Configure the MPU attributes for SRAM1 */
#if defined(MPU_WRITE_BACK_WRITE_ALLOCATE)
  MPU_Config_WB_WA();
#elif defined(MPU_WRITE_BACK_NO_WRITE_ALLOCATE)
  MPU_Config_WB_nWA(); 
#endif
  
  /* Configure the SRAM2 as non-cacheable memory */
  MPU_Config_nCacheable();

  /* STM32F7xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();

  /* Configure the system clock to 216 MHz */
  SystemClock_Config();
  
  /* Initialize LEDs */
  BSP_LED_Init(LED_GREEN);
  BSP_LED_Init(LED_ORANGE);
  BSP_LED_Init(LED_RED);
  BSP_LED_Init(LED_BLUE);
  
  /* Configure the Tamper push-button in GPIO Mode */
  BSP_PB_Init(BUTTON_TAMPER, BUTTON_MODE_GPIO);
  
  /* Configure the DMA stream for Memory to Memory transfer */
  DMA_Config();
  
  /*## -1- DMA Transfer 1: aSRC_Const_Buffer1 (FLASH) --> aDST_Buffer1 (SRAM1) #######*/
  /*##################################################################################*/
  
  /* Read the Destination Buffer to ensure that it will be put in DCACHE */
  for (i=0; i<BUFFER_SIZE; i++)
  {
    tempValue += aDST_Buffer1[i];
  }
  
  /* Start the DMA transfer, and compare source and destination buffers */
  if (DMA_StartAndCompare((uint32_t *)aSRC_Const_Buffer1, aDST_Buffer1, BUFFER_SIZE) != 0)
  {
    /* Wrong behaviour: Turn on LED_RED */
    BSP_LED_On(LED_RED);
  }
  else
  {
    /* Correct behaviour: Turn on LED_GREEN */
    BSP_LED_On(LED_GREEN);
  }

  /*## -2- DMA Transfer 2: aSRC_Buffer2 (SRAM1) --> aDST_NonCacheable_Buffer2 (SRAM2) */
  /*##################################################################################*/
  
  /* Fill the Source Buffer: it will be compared with the destination buffer */
  for (i=0; i<BUFFER_SIZE; i++)
  {
    aSRC_Buffer2[i] = i;    
  }
  
  /* Start the DMA transfer, and compare source and destination buffers */
  if (DMA_StartAndCompare(aSRC_Buffer2, aDST_NonCacheable_Buffer2, BUFFER_SIZE) != 0)
  {
    /* Wrong behaviour: Turn on LED_ORANGE */
    BSP_LED_On(LED_ORANGE);
  }
  else
  {
    /* Correct behaviour: Turn on LED_BLUE */
    BSP_LED_On(LED_BLUE);
  }
  
  /*## -3- Wait for Tamper Key press / release  ######################################*/
  /*##################################################################################*/
  
  /* Wait for Tamper Key press before starting the Cache maintenance */
  while (BSP_PB_GetState(BUTTON_TAMPER) == RESET)
  {
  }
  
  /* Wait for Tamper Key to be released before starting the Cache maintenance */
  while (BSP_PB_GetState(BUTTON_TAMPER) == SET)
  {
  }
  
  /* Turn off leds */
  BSP_LED_Off(LED_GREEN);
  BSP_LED_Off(LED_ORANGE);
  BSP_LED_Off(LED_RED);
  BSP_LED_Off(LED_BLUE);
  
  /*## -4- Do Cache maintenance for Transfer 1  ######################################*/
  /*##################################################################################*/
  
  /*
  CPU Data Cache maintenance:  
  It is recommended to invalidate the destination buffer in Data cache after a DMA transfer.
  This guarantees up-to-date data when CPU access to the destination buffer located in the
  SRAM1 (which is cacheable).
  */
  
  /* Invalidate aDST_Buffer1 in DCACHE: (BUFFER_SIZE * 4) bytes */ 
  SCB_InvalidateDCache_by_Addr(aDST_Buffer1, BUFFER_SIZE * 4); 
  
  /* Compare Source and Destination buffers */
  if(memcmp(aSRC_Const_Buffer1, aDST_Buffer1, BUFFER_SIZE * 4) != 0)
  {
    /* Wrong Comparison: Turn on LED_RED */
    BSP_LED_On(LED_RED);
  }
  else
  {
    /* Right comparison: Turn on LED_GREEN */  
    BSP_LED_On(LED_GREEN);
  }
  
  /*## -5- Do Cache maintenance for Transfer 2  ######################################*/
  /*##################################################################################*/
  
  /*
  CPU Data Cache maintenance:  
  It is recommended to clean the source buffer in CPU Data cache before starting 
  the DMA transfer. As the source buffer may be used by the CPU and modified 
  locally in DCACHE. The cache clean guarantees up-to-date data when DMA accesses 
  to the source buffer located in the SRAM1 (which is cacheable).
  */
  
  /* Clean aSRC_Buffer2 in DCACHE: (BUFFER_SIZE * 4) bytes */ 
  SCB_CleanDCache_by_Addr(aSRC_Buffer2, BUFFER_SIZE * 4);
  
  /* Re-Start the DMA transfer, and compare source and destination buffers */
  if (DMA_StartAndCompare(aSRC_Buffer2, aDST_NonCacheable_Buffer2, BUFFER_SIZE) != 0)
  {
    /* Wrong behaviour: Turn on LED_ORANGE */
    BSP_LED_On(LED_ORANGE);
  }
  else
  {
    /* Correct behaviour: Turn on LED_BLUE */
    BSP_LED_On(LED_BLUE);
  }
  
  /* Infinite loop */
  while (1)
  {
  }
}

/**
  * @brief  Configure the DMA controller
  * @note  This function is used to :
  *        -1- Enable DMA2 clock
  *        -2- Select the DMA functional Parameters
  *        -3- Select the DMA instance to be used for the transfer
  *        -4- Select Callbacks functions called after Transfer complete and
               Transfer error interrupt detection
  *        -5- Initialize the DMA stream
  *        -6- Configure NVIC for DMA transfer complete/error interrupts
  * @param  None
  * @retval None
  */
static void DMA_Config(void)
{
  /*## -1- Enable DMA2 clock #################################################*/
  __HAL_RCC_DMA2_CLK_ENABLE();

  /*##-2- Select the DMA functional Parameters ###############################*/
  DmaHandle.Init.Channel = DMA_CHANNEL;                     /* DMA_CHANNEL_0                    */
  DmaHandle.Init.Direction = DMA_MEMORY_TO_MEMORY;          /* M2M transfer mode                */
  DmaHandle.Init.PeriphInc = DMA_PINC_ENABLE;               /* Peripheral increment mode Enable */
  DmaHandle.Init.MemInc = DMA_MINC_ENABLE;                  /* Memory increment mode Enable     */
  DmaHandle.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD; /* Peripheral data alignment : Word */
  DmaHandle.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;    /* memory data alignment : Word     */
  DmaHandle.Init.Mode = DMA_NORMAL;                         /* Normal DMA mode                  */
  DmaHandle.Init.Priority = DMA_PRIORITY_VERY_HIGH;         /* priority level : very high       */
  DmaHandle.Init.FIFOMode = DMA_FIFOMODE_ENABLE;            /* FIFO mode enabled                */
  DmaHandle.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_1QUARTERFULL; /* FIFO threshold: 1/4 full   */
  DmaHandle.Init.MemBurst = DMA_MBURST_SINGLE;              /* Memory burst                     */
  DmaHandle.Init.PeriphBurst = DMA_PBURST_SINGLE;           /* Peripheral burst                 */

  /*##-3- Select the DMA instance to be used for the transfer : DMA2_Stream0 #*/
  DmaHandle.Instance = DMA_INSTANCE;

  /*##-4- Initialize the DMA stream ##########################################*/
  if (HAL_DMA_Init(&DmaHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }

  /*##-5- Select Callbacks functions called after Transfer complete and Transfer error */
  HAL_DMA_RegisterCallback(&DmaHandle, HAL_DMA_XFER_CPLT_CB_ID, TransferComplete);
  HAL_DMA_RegisterCallback(&DmaHandle, HAL_DMA_XFER_ERROR_CB_ID, TransferError);
  
  /*##-6- Configure NVIC for DMA transfer complete/error interrupts ##########*/
  /* Set Interrupt Group Priority */
  HAL_NVIC_SetPriority(DMA_INSTANCE_IRQ, 0, 0);

  /* Enable the DMA STREAM global Interrupt */
  HAL_NVIC_EnableIRQ(DMA_INSTANCE_IRQ);
}

/**
  * @brief  Start the DMA Transfer and compares source and destination buffers
  * @note  This function is used to :
  *        -1- Reset transfer variables
  *        -2- Start the DMA transfer using the interrupt mode
  *        -3- wait until DMA transfer complete or transfer error
  *        -4- Turn LED_ORANGE on in case of DMA transfer error
  *        -5- Compare Source and Destination buffers
  * @param  SrcBuffer: The source memory Buffer address
  * @param  DstBuffer: The destination memory Buffer address
  * @param  BuuferLength: The length of data to be transferred from source to destination
  * @retval Status (0 or 1)
  */
static uint32_t DMA_StartAndCompare(uint32_t* SrcBuffer, uint32_t* DstBuffer, uint32_t BufferLength)
{
  /* Reset transfer variables */
  transferCompleteDetected = 0;
  transferErrorDetected    = 0;
  
  /* Start the DMA transfer */
  if (HAL_DMA_Start_IT(&DmaHandle, (uint32_t)SrcBuffer, (uint32_t)DstBuffer, BufferLength) != HAL_OK)
  {
    /* Transfer Error */
    Error_Handler();
  }
  
  while ((transferCompleteDetected == 0) && (transferErrorDetected == 0))
  {
    /* wait until DMA transfer complete or transfer error */
  }
  
  if (transferErrorDetected == 1)
  {
    /* DMA transfer error */
    return 1;
  }
  
  /* Compare Source and Destination buffers */
  if(memcmp(SrcBuffer, DstBuffer, BufferLength * 4) != 0)
  {
    /* Wrong comparison */
    return 1;
  }
  else
  {
    /* Right comparison */  
    return 0;
  }
}

/**
  * @brief  DMA conversion complete callback
  * @note   This function is executed when the transfer complete interrupt
  *         is generated
  * @retval None
  */
static void TransferComplete(DMA_HandleTypeDef *DmaHandle)
{
  transferCompleteDetected = 1;
}

/**
  * @brief  DMA conversion error callback
  * @note   This function is executed when the transfer error interrupt
  *         is generated during DMA transfer
  * @retval None
  */
static void TransferError(DMA_HandleTypeDef *DmaHandle)
{
  transferErrorDetected = 1;
}

/**
  * @brief  System Clock Configuration
  *         The system Clock is configured as follow : 
  *            System Clock source            = PLL (HSE)
  *            SYSCLK(Hz)                     = 216000000
  *            HCLK(Hz)                       = 216000000
  *            AHB Prescaler                  = 1
  *            APB1 Prescaler                 = 4
  *            APB2 Prescaler                 = 2
  *            HSE Frequency(Hz)              = 25000000
  *            PLL_M                          = 25
  *            PLL_N                          = 432
  *            PLL_P                          = 2
  *            PLL_Q                          = 9
  *            PLL_R                          = 7
  *            VDD(V)                         = 3.3
  *            Main regulator output voltage  = Scale1 mode
  *            Flash Latency(WS)              = 7
  * @param  None
  * @retval None
  */
static void SystemClock_Config(void)
{
  RCC_ClkInitTypeDef RCC_ClkInitStruct;
  RCC_OscInitTypeDef RCC_OscInitStruct;
  HAL_StatusTypeDef  ret = HAL_OK;
  
  /* Enable Power Control clock */
  __HAL_RCC_PWR_CLK_ENABLE();
  
  /* The voltage scaling allows optimizing the power consumption when the device is 
     clocked below the maximum system frequency, to update the voltage scaling value 
     regarding system frequency refer to product datasheet.  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /* Enable HSE Oscillator and activate PLL with HSE as source */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 25;
  RCC_OscInitStruct.PLL.PLLN = 432;  
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 9;
  RCC_OscInitStruct.PLL.PLLR = 7;
  
  ret = HAL_RCC_OscConfig(&RCC_OscInitStruct);
  if(ret != HAL_OK)
  {
    while(1) { ; }
  }
  
  /* Activate the OverDrive to reach the 216 MHz Frequency */  
  ret = HAL_PWREx_EnableOverDrive();
  if(ret != HAL_OK)
  {
    while(1) { ; }
  }
  
  /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */
  RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;  
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; 
  
  ret = HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7);
  if(ret != HAL_OK)
  {
    while(1) { ; }
  }  
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @param  None
  * @retval None
  */
static void Error_Handler(void)
{
  /* User may add here some code to deal with this error */
  while(1)
  {
  }
}

/**
  * @brief  CPU L1-Cache enable.
  * @param  None
  * @retval None
  */
static void CPU_CACHE_Enable(void)
{
  /* Enable I-Cache */
  SCB_EnableICache();

  /* Enable D-Cache */
  SCB_EnableDCache();
}

#ifdef  USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t* file, uint32_t line)
{ 
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif

/**
  * @}
  */

/**
  * @}
  */

